package com.zxy.ziems.server.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.btp.common.exception.ConditionException;
import com.zxy.ziems.server.convert.DictConvert;
import com.zxy.ziems.server.domain.Dict;
import com.zxy.ziems.server.dto.DictDto;
import com.zxy.ziems.server.mapper.DictMapper;
import com.zxy.ziems.server.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author bhg
 * @date 2023/3/13
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdate(DictDto dictDto) {
        String dictId = dictDto.getDictId();
        Dict dict = DictConvert.INSTANCE.DictDtoToDict(dictDto);
        checkNameAndCode(dictDto);
        if (StrUtil.isEmpty(dictId)) {
            dictMapper.insert(dict);
        }else {
            dictMapper.updateById(dict);
        }
    }

    private void checkNameAndCode(DictDto dictDto) {
        String dictId = dictDto.getDictId();
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(StrUtil.isNotEmpty(dictId),Dict::getDictId,dictId)
                .eq(Dict::getDictName,dictDto.getDictName());
        Long count = dictMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new ConditionException("字典名称不能重复，请修改");
        }
        queryWrapper.clear();
        queryWrapper.lambda().ne(StrUtil.isNotEmpty(dictId),Dict::getDictId,dictId)
                .eq(Dict::getDictCode,dictDto.getDictCode());
        Long countCode = dictMapper.selectCount(queryWrapper);
        if (countCode > 0) {
            throw new ConditionException("字典编码不能重复，请修改");
        }
    }
}
